/**
* COPYRIGHT. whx. ALL RIGHTS RESERVED.
* Project: just-core
* Author: whx <harrywu304@gmail.com>
* Create On: Apr 18, 2012 3:08:14 PM
*/

package org.justframework.api.rpc;

import java.util.Map;

import org.justframework.api.connector.ClientConnector;
import org.justframework.api.connector.ClientConnectorFactory;
import org.justframework.api.connector.Request;
import org.justframework.api.connector.Response;
import org.justframework.api.exception.ConnectFailureException;
import org.justframework.core.RequestRender;
import org.justframework.core.helper.ConfigHelper;
import org.justframework.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class RpcServiceImpl implements RpcService {
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(RpcServiceImpl.class);
	
	/**
	 * schema client connector mapping
	 */
	private static Map<String, String> schemaClientMapping;
	
	static {
		//get schema client mapping
		schemaClientMapping = ConfigHelper.getMap("schema_client_connector_mapping");
	}
	
	/**
	 * render request and do real rpc
	 * @param request
	 * @return
	 */
	public Response rpc(Request request){
		Response response = null;
		try{
			//render request
			RequestRender.renderRequest(request);
			//get connector 
			String klassName = getClientClass(request.getUri().getScheme());
			ClientConnector clientConnector = ClientConnectorFactory.getClientConnector(klassName);
			//do rpc request
			response = clientConnector.rpc(request);
		}catch(ConnectFailureException cfe){
			logger.error("Connect to host [{}] fail",cfe.getHostPort(),cfe);
			throw cfe;
		}
		return response;
	}
	
	/**
	 * get client class name by schema
	 * @param schema 
	 * @return client class name
	 */
	private static String getClientClass(String schema){
		if(StringUtil.isNullOrBlank(schema)){
			schema = "default";
		}
		return schemaClientMapping.get(schema.toLowerCase());
	}
}
